/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-17 18:34:00
 ******************************************************************************/
package cn.com.xy.sms.sdk.service.pubInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.NetQueryTimeManager;
import cn.com.xy.sms.sdk.db.entity.SmsParseRecorder;
import cn.com.xy.sms.sdk.db.entity.UpdateTaskManager;
import cn.com.xy.sms.sdk.db.entity.pubinfo.PubInfoManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;
import cn.com.xy.sms.sdk.net.util.ServerUtil;
import cn.com.xy.sms.sdk.util.JsonUtil;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;
import cn.com.xy.sms.util.UUIDUtils;
import cn.com.xy.sms.sdk.util.ConversationManager;
/* SDK-538 huangzhiqiang 20160714 start */
import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.dex.DexUtil;
/* SDK-538 huangzhiqiang 20160714 end */

/* SDK-616 hewengao 20160918 start */
import cn.com.xy.sms.sdk.threadpool.SmartSmsThreadPoolManager;
/* SDK-616 hewengao 20160918 end */

public class PubInfoNetService {
    /* SDK-397 hewengao 20160527 start */
//    static final ExecutorService mUploadPubInfoPool = Executors.newFixedThreadPool(1);
    /* SDK-397 hewengao 20160527 start */
    private static final Map<String, Boolean> UPLOAD_TASK_RUNNING = new HashMap<String, Boolean>();

    public static final int CB_TYPE_PUB_INFO = 0;

    public static final int CB_TYPE_MENU = 1;

    public static final int CB_TYPE_CHECK_UPDATE = 2;

    /**
     * activity -> ParseManager.queryPublicInfo ->
     * PubInfoService.queryPublicInfo ->
     * 
     * 
     * 
     * it will execute PubInfoManager.savaPubInfo(pubInfo, num, cnum, areaCode)
     * 
     * and save data in table tb_public_info/tb_public_num_info
     * 
     * @isReturnName 是否返回企业名字
     * @param num
     * @param cnum
     * @param areaCode
     * @param iccid
     * @param type
     * @param callBackWithResult
     * @param callBackType 0:企业资料 1:菜单
     */
    /* SDK-397 huangzhiqiang 20160524 start */
    public static void queryPubInfoRequest(final boolean isReturnName, final String num, final String cnum,
            final String areaCode, final String iccid, final String type, final XyCallBack callBackWithResult,
            final int callBackType, final boolean newThread, final boolean hasData, final boolean needUpdateNow) {

        try {
            if (!needUpdateNow && !NetQueryTimeManager.isAllowQuery(num, areaCode, hasData)) {
//                LogManager.e("pubInfo", "!!!!!!!!!! queryPubInfoRequest num: " + num + " areaCode: " + areaCode);
                XyUtil.doXycallBack(callBackWithResult, "");
                return;
            }
    /* SDK-397 huangzhiqiang 20160524 end */
//            LogManager.e("pubInfo", "########## queryPubInfoRequest num: " + num + " areaCode: " + areaCode);
            NetUtil.requestTokenIfNeed(iccid);
            /*SDK-431 songzhirong 20160530 start*/
            final String uuid = UUIDUtils.uniqId();
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.sdk.service.pubInfo.PubInfoNetService", "queryPubInfoRequest",isReturnName,num, cnum,
                     areaCode,  iccid,  type,  callBackWithResult,
                     callBackType,  newThread,  hasData,  needUpdateNow);  
            /*SDK-431 songzhirong 20160530 end*/

            XyCallBack whileNetCompletedCallBack = new XyCallBack() {
                @Override
                public void execute(Object... resObjs) {
                    /* SDK-538 huangzhiqiang 20160714 start */
                    resetLastNetQueryTimeIfNeed(num, areaCode, resObjs);
                    /* SDK-538 huangzhiqiang 20160714 end */

                    /*SDK-431 songzhirong 20160530 start*/
                    ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.sdk.service.pubInfo.PubInfoNetService", "queryPubInfoRequest",isReturnName,num, cnum,
                            areaCode,  iccid,  type,  callBackWithResult,
                            callBackType,  newThread,  hasData,  needUpdateNow,resObjs);  
                    /*SDK-431 songzhirong 20160530 end*/
//                    LogManager.d("duoqu_test", "开始处理网络返回数据");
                    Object obj = handleNetWorkResponse(null, isReturnName, num, cnum, areaCode, iccid,
                            callBackWithResult, callBackType, resObjs);
                    if (obj != null && CB_TYPE_PUB_INFO == callBackType) {
                        // addUploadPubInfoSignTask(getNeedUploadSignNum(resObjs));

                        JSONObject pubInfo = PubInfoManager.queryPubInfoByNum(num, areaCode, Integer.valueOf(type));
                        if (callBackWithResult != null) {
                            /*SDK-502 zhaojiangwei 20160622 start */
                            String res = JsonUtil.pubInfoToJson(pubInfo, num, areaCode);
                            /*SDK-502 zhaojiangwei 20160622 end */
                            callBackWithResult.execute(res);
                        }
                    }
                }
            };

            if (NetUtil.isEnhance()) {
                /* SDK-504 huangzhiqiang 20160623 start */
                String dataString = ServerUtil.QueryPubInfoRequest(num, cnum, areaCode, iccid, type);
                if (!StringUtils.isNull(dataString)) {
                    // 单个查询，受网络开关控制
                    NetUtil.executePubNumServiceHttpRequest(dataString, "990005", whileNetCompletedCallBack, cnum,
                            newThread, false, NetUtil.REQ_QUERY_PUBINFO, true);
                } else {
                    XyUtil.doXycallBack(callBackWithResult, "");
                }
                /* SDK-504 huangzhiqiang 20160623 end */
            } else {
                XyUtil.doXycallBack(callBackWithResult, "");
            }

        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "PubInfoNetService queryPubInfoRequest: ", e);
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */
        }
    }

    /**
     * 描述：企业号批量更新接口
     * 
     * @param list
     * @param areaCode
     * @param iccid
     * @param type（1：电话号码，2：未定义 3：公众号ID ）
     * @return void
     */
    public static void queryPubInfoByList(final List<String> list, final String areaCode, final String iccid,
            final String type, final XyCallBack chkCallBack, final boolean isNewThread) {

        try {
            if (!NetUtil.checkAccessNetWork(1)) return;

            /*SDK-431 songzhirong 20160530 start*/
            final String uuid = UUIDUtils.uniqId();
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.sdk.service.pubInfo.PubInfoNetService", "queryPubInfoByList",list, areaCode,iccid,
                     type, chkCallBack,isNewThread);   
            /*SDK-431 songzhirong 20160530 end*/
            XyCallBack whileNetCompletedCallBack = new XyCallBack() {

                @Override
                public void execute(Object... obj) {
                    // addUploadPubInfoSignTask(getNeedUploadSignNum(obj));
                    /*SDK-431 songzhirong 20160530 start*/
                    ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.sdk.service.pubInfo.PubInfoNetService", "queryPubInfoByList",list, areaCode,iccid,
                             type, chkCallBack,isNewThread,obj); 
                    /*SDK-431 songzhirong 20160530 end*/
                    handleNetWorkResponse(list, false, null, null, areaCode, iccid, chkCallBack,
                            CB_TYPE_CHECK_UPDATE, obj);
                }
            };

            NetUtil.requestTokenIfNeed(iccid);
            String dataString = ServerUtil.QueryPubInfoWithListReqBody(list, null, areaCode, iccid, type);
            LogManager.d("queryPubInfo", "PubInfoNetService queryPubInfoByList dataString=",dataString);
            if (StringUtils.isNull(dataString)) {
                return;
            }

            // 批量更新，受网络类型开关控制，且仅wifi
            NetUtil.executePubNumServiceHttpRequest(dataString, "990005", whileNetCompletedCallBack, null,
                    isNewThread, false, NetUtil.REQ_QUERY_PUBINFO, true);
        

        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "PubInfoNetService queryPubInfoByList: ", e);
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */

        }
    }

    /**
     * 描述： while query succeed , it will execute
     * PubInfoManager.savaPubInfo(pubInfo, num, cnum, areaCode)
     * 
     * @param num
     * @param cnum
     * @param areaCode
     * @param iccid
     * @param type
     * @param callBack
     * @param callBackType
     * @param id
     * @return void
     */
    /* SDK-397 huangzhiqiang 20160524 start */
    public static void queryPubInfoRequestWithId(final String num, final String cnum, final String areaCode,
            final String iccid, String type, final XyCallBack callBack, final int callBackType, final String id, boolean needUpdateNow) {

        try {
            if (!needUpdateNow && !NetQueryTimeManager.isAllowQuery(num, areaCode, false)) {
                XyUtil.doXycallBackResult(callBack, -1, null, id);
                return;
            }
    /* SDK-397 huangzhiqiang 20160524 end */
            NetUtil.requestTokenIfNeed(iccid);
            XyCallBack callback = new XyCallBack() {
                @Override
                public void execute(Object... obj) {
                    /* SDK-538 huangzhiqiang 20160714 start */
                    resetLastNetQueryTimeIfNeed(num, areaCode, obj);
                    /* SDK-538 huangzhiqiang 20160714 end */

                    boolean iscall = false;
                    if (obj != null) {
                        String resutCode = obj[0].toString();

                        if (resutCode.equals("0") && obj.length == 2) {

                            String response = obj[1].toString();

                            Map<String, JSONObject> infoMap = ServerUtil.parsePubInfoRespose(response);
                            if (infoMap == null) {
                                return;
                            }

                            // addUploadPubInfoSignTask(getNeedUploadSignNum(obj));

                            Iterator<String> it = infoMap.keySet().iterator();
                            JSONObject pubInfo = infoMap.get(it.next()); // 用id保存成功与否状态
                            String respondCode = pubInfo.optString("id");
                            if (ServerUtil.CODE_SUCCESS.equals(respondCode)) {
                                PubInfoManager.savaPubInfo(pubInfo);
                                /* SDK-768 mobaohua 2017-05-03 start*/
                                PublicInfoCacheManager.updatePublicInfoDataCache(pubInfo);
                                /* SDK-768 mobaohua 2017-05-03 end*/
                                String result = null;
                                try {
                                    if (callBack != null) {
                                        if (callBackType == 0) {// 企业资料
                                            /*SDK-502 zhaojiangwei 20160622 start */
                                            result = JsonUtil.pubInfoToJson(pubInfo, num, areaCode);
                                            /*SDK-502 zhaojiangwei 20160622 end */
                                            iscall = true;
                                            XyUtil.doXycallBackResult(callBack, 0, result, id);
                                        } else if (callBackType == 1) {// 菜单
                                            String res = null;
                                            JSONArray pubMenuInfolist = pubInfo.optJSONArray("pubMenuInfolist");
                                            /* SDK-767 kangwenbo 20170504 start */
                                            pubMenuInfolist = changePubMenuInfoToJsonArray(num,pubInfo,pubMenuInfolist);
                                            /* SDK-767 kangwenbo 20170504 end */
                                            if (pubMenuInfolist != null && pubMenuInfolist.length() > 0) {

                                                res = pubMenuInfolist.toString();

                                            }
                                            iscall = true;

                                            XyUtil.doXycallBackResult(callBack, 0, res, id);

                                        }
                                    }
                                } catch (Throwable e) {
                                    LogManager.e(Constant.TAG, "PubInfoNetService queryPubInfoRequestWithId: ", e);
                                }
                                /*SDK-503 zhaojiangwei 20160624 start*/
                                /* SDK-723 quyi 20170214 start */
                                finally{
//                                    PubInfoManager.sendUpdatePubInfoCacheNotification(num,result);
                                    PubInfoManager.sendRemovePubInfoCacheNotification(num);
                                }
                                /* SDK-723 quyi 20170214 end */
                                /*SDK-503 zhaojiangwei 20160624 end*/
                            } else if (ServerUtil.CODE_TOKENOUT.equals(respondCode)) {
                                NetUtil.QueryTokenRequest(iccid);
                            }
                        }
                    }
                    if (!iscall) {
                        if (callBack != null) {
                            XyUtil.doXycallBackResult(callBack, -1, null, id);
                        }

                    }
                }
            };
            if (NetUtil.isEnhance()) {// 单个查询，受增强开关控制
                /* SDK-504 huangzhiqiang 20160623 start */
                String dataString = ServerUtil.QueryPubInfoRequest(num, cnum, areaCode, iccid, type);
                if (!StringUtils.isNull(dataString)) {
                    NetUtil.executePubNumServiceHttpRequest(dataString, "990005", callback, cnum, true, false,
                            NetUtil.REQ_QUERY_PUBINFO, true);
                } else {
                    XyUtil.doXycallBackResult(callBack, -1, null, id);
                }
                /* SDK-504 huangzhiqiang 20160623 end */
            } else {
                XyUtil.doXycallBackResult(callBack, -1, null, id);
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "PubInfoNetService queryPubInfoRequestWithId: ", e);
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */
        }
    }

    /**
     * 描述：处理网络响应
     * 
     * @param isReturnName
     * @param num
     * @param cnum
     * @param areaCode
     * @param iccid
     * @param callBackWithResult
     * @param callBackType 回调种类 0：更新单个企业资料 1：更新单个菜单资料 2：批量更新企业资料
     * @param resObjs
     * @return
     * @return 如果成功处理数据返回true
     */
    protected static Object handleNetWorkResponse(final List<String> list, final boolean isReturnName, final String num,
            final String cnum, final String areaCode, final String iccid, final XyCallBack callBackWithResult,
            final int callBackType, Object... resObjs) {
        try {
            Object pubRes = null;
            if (resObjs == null) {
                // 请求处理失败，需要更新查询标记
                if (callBackType == CB_TYPE_PUB_INFO || callBackType == CB_TYPE_CHECK_UPDATE) {
                    SmsParseRecorder.updateParseSmsRecord(false);
                }

                // callBackWithResult 不可以为空，为空直接返回
                if (callBackWithResult == null) {
                    return null;
                }
                // 正常情况下，有回调，resObjs就不会空，除非XyHttpRunnable有代码错误
                // 回调空，让发起回调者根据空的情况执行
                callBackWithResult.execute(-1);
                return null;

            } else {

                String resutCode = resObjs[0].toString();
                if (resutCode.equals("0") && resObjs.length == 2) {

                    String response = resObjs[1].toString();
                    // 更新数据最后更新的时间
                    PubInfoManager.updateUpdateInfoTime(list);

                    Map<String, JSONObject> infoMap = ServerUtil.parsePubInfoRespose(response);

                    if (infoMap == null || infoMap.size() == 0) {
                        // 回调空，让发起回调者根据空的情况执行，查询企业菜单某个接口是没把callback带过来的，这里判断非空才调用很重要
                        if (callBackWithResult != null) {
                            callBackWithResult.execute();
                        }

                        // 请求处理失败，需要更新查询标记
                        if (callBackType == CB_TYPE_PUB_INFO || callBackType == CB_TYPE_CHECK_UPDATE) {
                            SmsParseRecorder.updateParseSmsRecord(false);
                        }

                        return null;
                    }
                    Iterator<String> it = infoMap.keySet().iterator();

                    JSONObject pubInfo = infoMap.get(it.next());

                    String respondCode = pubInfo.optString("id");
                    if (ServerUtil.CODE_SUCCESS.equals(respondCode)) {
                        // 先回调再默默保存数据
                        try {
                            if (callBackWithResult != null) {
                                String res = "";
                                switch (callBackType) {
                                // 由于，单个查询，需要使用到号码的用途数据，用当前的返回值没有此数据。所以等入库完毕后重新查询。
                                case CB_TYPE_PUB_INFO:
                                    pubRes = pubInfo;
                                    break;
                                case CB_TYPE_MENU:
                                    String[] resultArr = new String[2];
                                    res = "";

                                        JSONArray pubMenuInfolist = pubInfo.optJSONArray("pubMenuInfolist");
                                       /* SDK-767 kangwenbo 20170504 start */
                                       pubMenuInfolist = changePubMenuInfoToJsonArray(num,pubInfo,pubMenuInfolist);
                                       /* SDK-767 kangwenbo 20170504 end */
                                    /*SDK-653 hewengao 20161025 start*/
                                    if (pubMenuInfolist != null && pubMenuInfolist.length() > 1) {
                                    /*SDK-653 hewengao 20161025 end*/
                                        if (isReturnName) {// 假如需要返回企业名字，把pubInfo传入
                                            resultArr[0] = pubInfo.optString("pubName");
                                            resultArr[1] = pubMenuInfolist.toString();
                                            XyUtil.doXycallBackResult(callBackWithResult, resultArr[0], resultArr[1]);
                                        } else {
                                            res = pubMenuInfolist.toString();
                                            XyUtil.doXycallBackResult(callBackWithResult, res,
                                                    pubInfo.optString("pubId"));

                                        }

                                    }

                                    break;
                                case CB_TYPE_CHECK_UPDATE:
                                    callBackWithResult.execute(infoMap);
                                    break;
                                default:
                                    break;
                                }

                            }

                            // 请求处理成功，更新数据
                            if (callBackType == CB_TYPE_PUB_INFO || callBackType == CB_TYPE_CHECK_UPDATE) {
                                SmsParseRecorder.updateParseSmsRecord(true);
                            }
                        } catch (Throwable e) {
                            // e.printStackTrace();
                            LogManager.e(Constant.TAG, "PubInfoNetService handleNetWorkResponse: ", e);

                            // 回调空，让发起回调者根据空的情况执行，查询企业菜单某个接口是没把callback带过来的，这里判断非空才调用很重要
                            if (callBackWithResult != null) {
                                callBackWithResult.execute("-1");
                            }

                            // 请求处理失败，需要更新查询标记
                            // 因为服务器已经接收到服务器了，这里抛出异常是客户端这边的，因为需要删除本地已经上传过的数据
                            if (callBackType == CB_TYPE_PUB_INFO || callBackType == CB_TYPE_CHECK_UPDATE) {
                                SmsParseRecorder.updateParseSmsRecord(true);
                            }
                        }
                        for (String key : infoMap.keySet()) {
                            PubInfoManager.savaPubInfo(infoMap.get(key));
                            /* SDK-768 mobaohua 2017-05-03 start*/
                            PublicInfoCacheManager.updatePublicInfoDataCache(infoMap.get(key));
                            /* SDK-768 mobaohua 2017-05-03 end*/
                        }
                    }

                    else if (ServerUtil.CODE_TOKENOUT.equals(respondCode)) {

                        NetUtil.QueryTokenRequest(iccid);
                    }

                    // 请求处理失败，需要更新查询标记
                    if (!ServerUtil.CODE_SUCCESS.equals(respondCode)) {
                        if (callBackType == CB_TYPE_PUB_INFO || callBackType == CB_TYPE_CHECK_UPDATE) {
                            SmsParseRecorder.updateParseSmsRecord(false);
                        }
                    }
                }
                return pubRes;
            }

        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "PubInfoNetService handleNetWorkResponse error:", e);
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */
        } finally {
            /* SDK-397 huangzhiqiang 20160526 start */
            PubInfoManager.sendRemovePubInfoCacheNotification(getNums(list));
            PubInfoManager.sendRemovePubInfoCacheNotification(num);
            /* SDK-397 huangzhiqiang 20160526 end */
        }
        return null;
    }

    private static JSONArray changePubMenuInfoToJsonArray(String num, JSONObject pubInfo, JSONArray pubMenuInfolist) {
        if (pubMenuInfolist != null && pubMenuInfolist.length() > 0) {
            int size = pubMenuInfolist.length();
            List<JSONObject> list = new ArrayList<JSONObject>();
            for (int i = 0; i < size; i++) {
                JSONObject pubMenuInfo = pubMenuInfolist.optJSONObject(i);
                List<JSONObject> item = getPubMenuInfo(pubMenuInfo);
                if (item != null)
                    list.addAll(item);
            }
            return createMenuDataAction(pubInfo.optString("pubId"), num, pubInfo.optString("versionCode"), pubInfo.optString("rid"),list);
        }
        return null;
    }

    public static List<JSONObject> getPubMenuInfo(JSONObject pubMenuInfo) {
        List<JSONObject> list = null;
        try {
            if (pubMenuInfo == null) {
                return null;
            }
            list = new ArrayList<JSONObject>();
            JSONArray secondmenuArray = pubMenuInfo.optJSONArray("secondmenu");
            if (secondmenuArray != null && secondmenuArray.length() > 0) {
                list.add(pubMenuInfo);
                int size = secondmenuArray.length();
                for (int i = 0; i < size; i++) {
                    JSONObject singlePubMenuInfo = secondmenuArray.getJSONObject(i);
                    list.add(singlePubMenuInfo);
                }
            } else {
                list.add(pubMenuInfo);
            }

        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e(Constant.TAG, "PubInfoNetService getPubMenuInfo: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        return list;
    }

    public static JSONArray createMenuDataAction(String pubId, String num, String versionCode, String rid, List<JSONObject> jsonList) {

        String companyNum = pubId + "_" + versionCode;
        try {
            String menuCode, menuName, menuType, actionData;
            HashMap<String, JSONObject> cacheData = new HashMap<String, JSONObject>();
            String nameKey = "name";
            String menuCodeKey = "menuCode";
            String typeKey = "type";
            String phoneNum = "phoneNum";
            String actionDataKey = "action_data";
            String secondMenuKey = "secondmenu";
            JSONArray jsonArr = new JSONArray();
            JSONObject jsonActionDataObject = new JSONObject();
            jsonActionDataObject.put("uiType", "MENU");
            jsonActionDataObject.put("phoneNum", num);
            jsonActionDataObject.put("companyNum", companyNum);
            jsonActionDataObject.put("rid", rid);

            HashSet<String> menuCodeSet = new HashSet<String>();
            for (JSONObject item :jsonList){
                menuCode = item.optString(menuCodeKey);
                if (menuCodeSet.contains(menuCode)) {
                    // PrintTestLogUtil.printTestLog("queryMenuDataAction",
                    // "已经包含了"+menuCode);
                    // 同一个menuCode，只会存在一个，出现多个，说明重复了。
                    continue;
                } else {
                    // PrintTestLogUtil.printTestLog("queryMenuDataAction",
                    // "还没有包含"+menuCode);
                    menuCodeSet.add(menuCode);
                }
                menuName = item.optString("menuName");
                menuType = item.optString("menuType");
                actionData = item.optString("actionData");
//                jsonActionDataObject.put(nameKey, menuName);
                jsonActionDataObject.put(menuCodeKey, menuCode);


                if (actionData != null) {
                    jsonActionDataObject.put("menu_item_action_data", actionData);
                    actionData = jsonActionDataObject.toString();
                }
                if (menuCode.length() == 2) {
                    JSONObject jsonObject = null;
                    if (!"menu".equalsIgnoreCase(menuType)) {
                        jsonObject = JsonUtil.getJsonObject(nameKey, menuName, typeKey, menuType, actionDataKey, actionData);
                    } else {
                        jsonObject = JsonUtil.getJsonObject(nameKey, menuName, typeKey, menuType);
                        jsonObject.put(secondMenuKey, new JSONArray());
                        cacheData.put(menuCode, jsonObject);
                    }
                    if (jsonObject != null) {
                        jsonArr.put(jsonObject);
                    }
                } else if (menuCode.length() == 4) {
                    JSONObject jsonObject = JsonUtil.getJsonObject(nameKey, menuName, typeKey, menuType, actionDataKey, actionData);
                    JSONObject parentObj = cacheData.get(menuCode.substring(0, 2));
                    JSONArray secondjsonArr = parentObj.optJSONArray(secondMenuKey);
                    secondjsonArr.put(jsonObject);
                }
            }
            cacheData.clear();
            menuCodeSet.clear();
            return jsonArr;
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "PubInfoNetService createMenuDataAction: ", e);
        }
        return null;
    }




    /*SDK-495 20160620 huangzhiqiang start*/
    /**
     * 从企业的基本json数据中取企业号码
     */
    private static List<String> getNums(List<String> jsonList) {
        if (jsonList == null || jsonList.size() == 0) {
            return null;
        }
        List<String> nums = new ArrayList<String>();
        for (String jsonStr : jsonList) {
            try {
                String num = new JSONObject(jsonStr).getString("num");
                if (!StringUtils.isNull(num)) {
                    nums.add(num);
                }
            }
            catch (Throwable e) {
                LogManager.e(Constant.TAG, "PubInfoNetService getNums error:", e);
            }
        }
        return nums;
    }
    /*SDK-495 20160620 huangzhiqiang end*/

    /* SDK-421 huangzhiqiang 20160525 start */
    /**
     * 分片数据上传
     */
    public static void uploadShard() {
        uploadPubInfo(UpdateTaskManager.TaskGroup.UPLOAD_SHARD);
    }
    /* SDK-421 huangzhiqiang 20160525 end */

    /* SDK-397 huangzhiqiang 20160524 start */
    /**
     * 公众号明文签名上传
     */
    public static void uploadPubInfoSign() {
        uploadPubInfo(UpdateTaskManager.TaskGroup.UPLOAD_PUBINFO_SIGN);
    }

    /**
     * 公众号退订指令上传
     */
    public static void uploadPubInfoCmd() {
        uploadPubInfo(UpdateTaskManager.TaskGroup.UPLOAD_PUBINFO_CMD);
    }

    /**
     * 上传公众号信息
     * 
     * @param taskGroup
     */
    private static void uploadPubInfo(final UpdateTaskManager.TaskGroup taskGroup) {
        if (taskGroup == null) {
            return;
        }
        final String taskType = taskGroup.toString();
        /* SDK-397 hewengao 20160527 start */
        synchronized (PubInfoService.mPubBackRunnable1) {
        /* SDK-397 hewengao 20160527 end */
            Boolean uploadTaskRunning = UPLOAD_TASK_RUNNING.get(taskType);
            if (uploadTaskRunning != null && uploadTaskRunning) {
                return;
            }
            UPLOAD_TASK_RUNNING.put(taskType, true);
        }
        /* SDK-616 hewengao 20160918 start */
        SmartSmsThreadPoolManager.mUploadPubInfoPool.execute(new Runnable() {
        /* SDK-616 hewengao 20160918 end */
            public void run() {
                try {
                    /* SDK-616 hewengao 20160918 start */
                    SmartSmsThreadPoolManager.setThreadNameAndPriority(SmartSmsThreadPoolManager.TNAME_UPLOAD_PUBINFO, android.os.Process.THREAD_PRIORITY_BACKGROUND);
                    Thread.sleep(2000);
                    /* SDK-616 hewengao 20160918 end */
                    UpdateTaskManager.doTask(taskGroup);
                } catch (Throwable e) {
                    LogManager.e(Constant.TAG, "PubInfoNetService uploadPubInfo error:", e);
                } finally {
                    /* SDK-397 hewengao 20160527 start */
                    synchronized (PubInfoService.mPubBackRunnable1) {
                    /* SDK-397 hewengao 20160527 end */
                        UPLOAD_TASK_RUNNING.put(taskType, false);
                    }
                }
            }
        });
    }
    /* SDK-397 huangzhiqiang 20160524 end */

    /* SDK-538 huangzhiqiang 20160714 start */
    /**
     * 如果是断网而导致查询失败，重新设置最近一次网络接口查询时间，以便能够更快的重新查询网络接口
     * 
     * @param num
     * @param areaCode
     * @param resultObj
     */
    private static void resetLastNetQueryTimeIfNeed(String num, String areaCode, Object[] resultObj) {
        if (resultObj == null || resultObj.length < 1) {
            return;
        }
        try {
            int resultCode = (Integer) resultObj[0];
            // 不是连接超时或请求异常，不需要进行网络接口查询时间重设
            if (resultCode == NetUtil.HTTP_CONN_OUTTIME || resultCode == NetUtil.HTTP_THROWS_EXCEPTION) {
                // 连接超时或出现异常代表可能为断网而导致查询失败，重置网络接口查询时间
                long requeryPubInfoCycle = DexUtil.getUpdateCycleByType(
                        OnlineUpdateCycleConfigInterface.TYPE_NET_ERROR_REQUERY_PUBINFO_CYCLE, 2 * Constant.HOUR);
                long pubInfoQueryCycle = DexUtil.getUpdateCycleByType(
                        OnlineUpdateCycleConfigInterface.TYPE_BATCH_PUBLIC_NUM_INFO_UPDATE_CYCLE, Constant.month);
                long newNetQueryTime = System.currentTimeMillis() - (pubInfoQueryCycle - requeryPubInfoCycle);
                NetQueryTimeManager.insertOrUpdateNetQueryTime(num, areaCode, 0, newNetQueryTime);
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "PubInfoNetService resetLastNetQueryTimeIfNeed error:", e);
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */
        }
    }
    /* SDK-538 huangzhiqiang 20160714 end */
}
